<template>
  <canvas
    v-if="canvasId"
    class="ec-canvas"
    :id="canvasId"
    :canvasId="canvasId"
    @touchstart="touchStart"
    @touchmove="touchMove"
    @touchend="touchEnd"
    @error="error">
  </canvas>
</template>

<script>
import WxCanvas from './wx-canvas';


function wrapTouch(e) {
  for (let i = 0; i < e.mp.touches.length; i += 1) {
    const touch = e.mp.touches[i];
    touch.offsetX = touch.x;
    touch.offsetY = touch.y;
  }
  return e;
}

export default {
  name: "mpvueEcharts",
  props: {
    canvasId: {
      type: String,
      default: 'ec-canvas',
    },
    lazyLoad: {
      type: Boolean,
      default: false,
    },
    disableTouch: {
      type: Boolean,
      default: false,
    },
    throttleTouch: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['init'],
  mounted() {
    if (!this.lazyLoad) this.init();
  },
  methods: {
    init() {
      const version = wx.version.version.split('.').map(n => parseInt(n, 10));
      const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9)
        || (version[0] === 1 && version[1] === 9 && version[2] >= 91);
      if (!isValid) {
        console.error('微信基础库版本过低，需大于等于 1.9.91。');
        return;
      }

      const { canvasId } = this;
      this.ctx = wx.createCanvasContext(canvasId, this);

      const canvas = new WxCanvas(this.ctx, canvasId);

      // echarts.setCanvasCreator(() => canvas);

      const query = wx.createSelectorQuery().in(this);
      query.select(`#${canvasId}`).boundingClientRect((res) => {
        if (!res) {
          setTimeout(() => this.init(), 50);
          return;
        }

        const { width, height } = res;

        this.width = width;
	      this.height = height;

        this.$emit('init', {
          canvas,
          width,
          height
        });

        this.canvas = canvas;
        if (!canvas.chart) {
          return;
        }

        const { handler } = canvas.chart._zr;

        this.handler = handler;
        this.processGesture = handler.proxy.processGesture || (() => {});
      }).exec();
    },
    canvasToTempFilePath(opt) {
      const { canvasId } = this;
      this.ctx.draw(true, () => {
        wx.canvasToTempFilePath({
          canvasId,
          ...opt,
        });
      });
    },
    touchStart(e) {
      const { disableTouch, canvas } = this;
      const touches = e.touches || e.mp.touches;
      e.mp = e;
      if (!canvas || disableTouch || !canvas.chart || !touches.length) return;
      const touch = touches[0];
      this.handler.dispatch('mousedown', Object.assign({
        zrX: touch.x,
        zrY: touch.y,
      }, e));
      this.handler.dispatch('mousemove', Object.assign({
        zrX: touch.x,
        zrY: touch.y,
      }, e));
      this.processGesture(wrapTouch(e), 'start');
    },
    touchMove(e) {
      const {
        disableTouch, throttleTouch, canvas, lastMoveTime,
      } = this;
      const touches = e.touches || e.mp.touches;
      e.mp = e;
      if (!canvas || disableTouch || !canvas.chart || !touches.length) return;

      if (throttleTouch) {
        const currMoveTime = Date.now();
        if (currMoveTime - lastMoveTime < 150) return;
        this.lastMoveTime = currMoveTime;
      }

      const touch = touches[0];

      this.handler.dispatch('mousemove', Object.assign({
        zrX: touch.x,
        zrY: touch.y,
      }, e));
      this.processGesture(wrapTouch(e), 'change');
    },
    touchEnd(e) {
      const { disableTouch, canvas } = this;
      if (!canvas || disableTouch || !canvas.chart) return;
      const changedTouches = e.changedTouches || e.mp.changedTouches;
      e.mp = e;
      const touch = changedTouches ? changedTouches[0] : {};
      this.handler.dispatch('mouseup', Object.assign({
        zrX: touch.x,
        zrY: touch.y,
      }, e));
      this.handler.dispatch('click', Object.assign({
        zrX: touch.x,
        zrY: touch.y,
      }, e));
      this.processGesture(wrapTouch(e), 'end');
    },
  },
};
</script>

<style scoped>
.ec-canvas {
  width: 100%;
  height: 100%;
}
</style>
